package Servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    private ObjectMapper objectMapper=new ObjectMapper();



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");


        User user=Util.checkLogin(req);
        if(user==null){
            resp.setStatus(403);
            return;
        }





        BlogDao blogDao=new BlogDao();
        String blogId=req.getParameter("blogId");
        if(blogId==null||blogId.equals("")){
            List<Blog> blogs=blogDao.selectAll();
            String jsonString=objectMapper.writeValueAsString(blogs);
            resp.getWriter().write(jsonString);
        }else{
            Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
            String jsonString=objectMapper.writeValueAsString(blog);
            resp.getWriter().write(jsonString);
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        resp.setContentType("text/html;charset=utf8");

        User user=Util.checkLogin(req);
        if(user==null){
            resp.sendRedirect("blog_login.html");
            return;
        }
        String title=req.getParameter("title");
        String content=req.getParameter("content");
        if(title==null||title.equals("")||content==null||content.equals("")){
            String html="<h3>当前提交的标题或者正文为空！</h3>";
            resp.getWriter().write(html);
            return;
        }

        Blog blog=new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        blog.setPostTime(new Timestamp(System.currentTimeMillis()));
        BlogDao blogDao=new BlogDao();
        blogDao.insert(blog);

        resp.sendRedirect("blog_list.html");
    }
}
